package com.situ.mall.service.impl;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.dao.CartMapper;
import com.situ.mall.entity.Cart;
import com.situ.mall.entity.User;
import com.situ.mall.service.ICartService;

@Service
public class CartServiceImpl implements ICartService{

	@Autowired
	private CartMapper cartMapper;
	
	@Override
	public List<Cart> selectByUserId(Integer userId) {
		return cartMapper.selectByUserId(userId);
	}

	@Override
	public ServerResponse insert(Integer productId, Integer num, HttpSession session) {
		User user = (User)session.getAttribute("user");
		if(user == null) {
			return ServerResponse.createError("用户没有登陆");
		}
		Cart cart = new Cart();
		cart.setUserId(user.getId());
		cart.setProductId(productId);
		cart.setQuantity(num);
		cart.setChecked(1);
		
		// 判断这个商品是否在这个用户的购物车中
		Cart c = cartMapper.selectByUserIdAndProductId(user.getId(),productId);
		int count = 0;
		if (c != null) { // 这个商品已经在这个用户的购物车中，只需要更新一下数量
			count = cartMapper.updateQuantityByUserIdAndProductId(num,user.getId(),productId);
		} else {
			count = cartMapper.insert(cart);
		}
		
		if (count == 1) {
			return ServerResponse.createSuccess("加入购物车成功");
		}
		return ServerResponse.createError("加入购物车失败");
	}

	@Override
	public ServerResponse updateCheckStatus(Integer cartId, Integer checked) {
		int count = cartMapper.updateCheckStatus(cartId,checked);
		if(count == 1) {
			return ServerResponse.createSuccess("更新状态成功");
		}
		return ServerResponse.createError("更新状态失败");
	}

	@Override
	public ServerResponse deleteById(Integer cartId) {
		int count = cartMapper.deleteByPrimaryKey(cartId);
		if (count == 1) {
			return ServerResponse.createSuccess("删除成功");
		}
		return ServerResponse.createError("删除失败");
	}

	@Override
	public ServerResponse updateQuantity(Integer cartId, Integer num) {
		int count = cartMapper.updateQuantity(cartId, num);
		if (count == 1) {
			return ServerResponse.createSuccess("更新成功");
		}
		return ServerResponse.createError("更新失败");
	}

	@Override
	public List<Cart> selectCartByUserIdAndChecked(Integer userId) {
		List<Cart> list = cartMapper.selectCartByUserIdAndChecked(userId);
		return list;
	}

	@Override
	public ServerResponse updateCheckedStatusByUserId(Integer userId) {
		int count = cartMapper.updateCheckedStatusByUserId(userId);
		if(count != 0){
			return ServerResponse.createSuccess("全选成功");
		}
		return ServerResponse.createError("全选失败");
	}

}
